package com.magic.smartcity.view.more.bus

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.google.android.material.snackbar.Snackbar
import com.magic.smartcity.R
import com.magic.smartcity.beans.BusOrderBean
import com.magic.smartcity.databinding.FragmentBusSubmitOrderBinding
import com.magic.smartcity.utils.Constant
import com.magic.smartcity.view.more.viewmodels.BusViewModel

class BusSubmitOrderFragment : Fragment() {

    private lateinit var binding: FragmentBusSubmitOrderBinding

    private val viewModel by lazy {
        ViewModelProvider(this).get(BusViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.getLineById(arguments?.getInt("lineId")!!)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBusSubmitOrderBinding.inflate(layoutInflater)
        initView()
        return binding.root
    }

    private fun initView() {
        val busOrderBean: BusOrderBean = arguments?.getSerializable("busOrderBean") as BusOrderBean
        viewModel.busLine.observe(viewLifecycleOwner) {
            busOrderBean.path = it.name
            busOrderBean.price = it.price
            binding.busOrderBean = busOrderBean
            binding.lineStationStartEnd = "${it.first} —— ${it.end}"
        }
        binding.submitOrder.setOnClickListener {
            if (Constant.TOKEN != null)
                viewModel.addOrder(busOrderBean)
            else {
                val notLogin = Snackbar.make(binding.root, "未登录", Snackbar.LENGTH_SHORT)
                notLogin.setAction("去登陆") { v ->
                    Navigation.findNavController(it).navigate(R.id.loginFragment)
                }.show()
            }
        }
        viewModel.isAddOrderOk.observe(viewLifecycleOwner) {
            if (it) {
                Navigation.findNavController(binding.root)
                    .popBackStack(R.id.busDetailFragment, true)
                Toast.makeText(requireContext(), "提交成功", Toast.LENGTH_SHORT).show()
            } else Toast.makeText(requireContext(), "提交订单出错", Toast.LENGTH_SHORT).show()
        }
    }

}